import {
  addOrUpdate
} from '../../utils/api';
const app = getApp()

Page({
  /**
   * 页面的初始数据
   */
  data: {
    userInfo: {
      avatar: null,
      nickName: null,
    },
    StorageUserInfo: {},
    imgUrl: app.globalData.imgUrl,
    wxImgUrl: app.globalData.wxImgUrl,
    navBarHeight: '', //头高度
    statusBarHeight: '', //状态栏高度
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let navBarHeightinfo = app.publicFun.navBarHeightinfo()
    this.setData({
      navBarHeight: navBarHeightinfo[0],
      statusBarHeight: navBarHeightinfo[1]
    })
    const userInfo = JSON.parse(wx.getStorageSync('userInfo'));
    console.log(userInfo)
    this.setData({
      userInfo: {
        avatar: userInfo.profilePhoto,
        nickName: userInfo.nickName,
      },
      StorageUserInfo: userInfo,
    });
  },
  back() {
    wx.navigateBack({})
  },


  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {},

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {},

  handleUploadImage() {
    let a = this;
    wx.showActionSheet({
      itemList: ['从相册中选择', '拍照'],
      success: function (e) {
        console.log(e);
        //album:相册   //camera拍照
        e.cancel ||
          (0 == e.tapIndex ?
            a.chooseWxImageShop('album') :
            1 == e.tapIndex && a.chooseWxImageShop('camera'));
      },
    });
  },

  //a：选择的类型  //album:相册   //camera拍照
  chooseWxImageShop: function (a) {
    var e = this;
    wx.chooseImage({
      sizeType: ['original', 'compressed'],
      sourceType: [a], //类型
      count: 1,
      success: function (a) {
        if (a.tempFiles[0].size > 2097152) {
          wx.showModal({
            title: '提示',
            content: '选择的图片过大，请上传不超过2M的图片',
            showCancel: !1,
            success: function (a) {
              a.confirm;
            },
          });
        } else {
          //把图片上传到服务器
          e.upload_file(a.tempFilePaths[0]);
        }
      },
    });
  },

  upload_file: function (e) {
    wx.showLoading({
      title: '上传中',
    });
    wx.uploadFile({
      url: 'https://www.6laoyou.com/api/file/upload',
      filePath: e, //图片路径
      name: 'file',
      header: {
        'Content-Type': 'multipart/form-data',
        Authorization: 'Bearer ' + wx.getStorageSync('token'),
      },
      success: res => {
        wx.hideLoading();
        const result = JSON.parse(res.data);
        if (result.code === 200) {
          this.setData({
            userInfo: {
              avatar: result.data,
              nickName: this.data.userInfo.nickName,
            },
          });
          wx.showToast({
            title: '上传成功',
            icon: 'success',
            duration: 3000,
          });
        } else {
          wx.showToast({
            title: result.message,
            icon: 'success',
            duration: 3000,
          });
        }
      },
      fail: err => {
        wx.hideLoading();
        wx.showToast({
          title: '上传失败',
          icon: 'none',
          duration: 3000,
        });
      },
    });
  },

  // 昵称输入框事件
  handleInput(e) {
    this.setData({
      userInfo: {
        nickName: e.detail.value,
        avatar: this.data.userInfo.avatar
      }
    })
  },

  // 确定事件
  handleConfirm() {
    this.uploadUserInfo();
  },

  async uploadUserInfo() {
    const userInfo = JSON.parse(JSON.stringify(this.data.StorageUserInfo))
    console.log(userInfo)
    const params = {
      nickName: userInfo.nickName,
      profilePhoto: userInfo.avatar,
      userId: userInfo.id,
      userTypes: [1],
    };
    try {
      const result = await addOrUpdate(params);
      console.log(result)
      if (result) {
        wx.showToast({
          title: '修改成功',
          icon: 'none',
          duration: 1500,
        });
        userInfo.profilePhoto = this.data.userInfo.avatar
        userInfo.nickName = this.data.userInfo.nickName
        this.setData({
            StorageUserInfo: userInfo,
          },
          () => {
            wx.setStorageSync('userInfo', JSON.stringify(userInfo));
          },
        );
      }
    } catch (err) {
      console.log(err);
    }
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {},

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {},

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {},
});